using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace Acms.WebControls
{
    [ToolboxData("<{0}:DateTimeField runat=server></{0}:DateTimeField>")]
    public class DateTimeField : BaseDataField
    {
        protected override DataControlField CreateField()
        {
            return new DateTimeField();
        }

        public DateTime? MinValue{get;set;}
        public DateTime? MaxValue{get;set;}

        protected override object SaveViewState()
        {
            ViewState["MinValue"] = MinValue;
            ViewState["MaxValue"] = MaxValue;
            return base.SaveViewState();
        }

        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
            MinValue = ViewState["MinValue"] as DateTime?;
            MaxValue = ViewState["MaxValue"] as DateTime?;
        }

        protected override void InitEditControls(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
        {
            RadDateTimePicker ctrl = new RadDateTimePicker();
            ctrl.ID = GetUniqueId(rowIndex, "dt");
            if(MinValue.HasValue)
                ctrl.MinDate = this.MinValue.Value;
            if (MaxValue.HasValue)
                ctrl.MaxDate = this.MaxValue.Value;
            cell.Controls.Add(ctrl);
        }


        protected override void DataBindEditControls(DataControlFieldCell cell, object dataItem, int dataItemIndex, int displayIndex)
        {
            RadDateTimePicker ctrl = cell.Controls[0] as RadDateTimePicker;
            if (ctrl != null)
            {
                object val = null;
                if (dataItem != null)
                    val = DataBinder.Eval(dataItem, DataField);
                if (val != null && val is DateTime)
                {
                    ctrl.SelectedDate = (DateTime)val;
                }
                else if (val != null)
                {
                    ctrl.SelectedDate = DateTime.Parse(val.ToString());
                }
                else
                {
                    ctrl.SelectedDate = null;
                }
            }
        }
    }
}
